<template>
  <div class="workorder-detail">
    <a-card :bordered="false">
      <template #title>
        <span>工单详情</span>
        <a-tag :color="getStatusColor(workOrder?.status)" style="margin-left: 8px">
          {{ getStatusText(workOrder?.status) }}
        </a-tag>
      </template>

      <template #extra>
        <a-space>
          <a-button @click="router.back()"> 返回 </a-button>
          <a-button v-if="canEdit" type="primary" @click="handleEdit"> 编辑 </a-button>
        </a-space>
      </template>

      <a-skeleton :loading="loading" active>
        <a-descriptions :column="{ xs: 1, sm: 2, md: 3 }" bordered size="middle">
          <a-descriptions-item label="工单编号">
            {{ workOrder?.workOrderId }}
          </a-descriptions-item>
          <a-descriptions-item label="工单状态">
            <a-tag :color="getStatusColor(workOrder?.status)">
              {{ getStatusText(workOrder?.status) }}
            </a-tag>
          </a-descriptions-item>

          <a-descriptions-item label="报修人">
            {{ workOrder?.reporterNickName + ' (' + workOrder?.reporterAccount + ')' }}
          </a-descriptions-item>
          <a-descriptions-item label="处理人">
            {{ handlerUser }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话" style="white-space: pre-wrap">
            {{ contactPhone }}
          </a-descriptions-item>
          <a-descriptions-item label="维修类别">
            {{ workOrder?.categoryName }}
          </a-descriptions-item>
          <a-descriptions-item label="故障位置">
            {{ workOrder?.categoryName }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDate(workOrder?.createdAt) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDate(workOrder?.updatedAt) }}
          </a-descriptions-item>
          <a-descriptions-item label="问题描述" :span="3">
            {{ workOrder?.description }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 图片展示 -->
        <div v-if="workOrder?.imagesUrl" class="image-section">
          <h3>故障图片</h3>
          <a-image-preview-group>
            <a-image :src="workOrder.imagesUrl" :width="200" class="workorder-image" />
          </a-image-preview-group>
        </div>

        <!-- 处理记录 -->
        <div class="process-section">
          <h3>处理记录</h3>
          <a-timeline>
            <a-timeline-item color="green">
              <template #dot>
                <FileAddOutlined />
              </template>
              <div class="timeline-content">
                <div class="timeline-title">工单创建</div>
                <div class="timeline-time">{{ formatDate(workOrder?.createdAt) }}</div>
                <div class="timeline-desc">{{ workOrder?.reporterNickName }} 创建了工单</div>
              </div>
            </a-timeline-item>

            <!-- 这里应该根据实际处理记录动态生成 -->
            <a-timeline-item v-if="workOrder?.status !== WorkOrderStatus.PENDING" color="blue">
              <template #dot>
                <ToolOutlined />
              </template>
              <div class="timeline-content">
                <div class="timeline-title">开始处理</div>
                <div class="timeline-time">{{ formatDate(workOrder?.updatedAt) }}</div>
                <div class="timeline-desc">维修工 开始处理工单</div>
              </div>
            </a-timeline-item>

            <a-timeline-item
              v-if="
                workOrder?.status === WorkOrderStatus.COMPLETED ||
                workOrder?.status === WorkOrderStatus.REVIEWED
              "
              color="green"
            >
              <template #dot>
                <CheckCircleOutlined />
              </template>
              <div class="timeline-content">
                <div class="timeline-title">维修完成</div>
                <div class="timeline-time">{{ formatDate(workOrder?.updatedAt) }}</div>
                <div class="timeline-desc">维修工 完成了维修工作</div>
              </div>
            </a-timeline-item>

            <a-timeline-item v-if="workOrder?.status === WorkOrderStatus.REVIEWED" color="purple">
              <template #dot>
                <StarOutlined />
              </template>
              <div class="timeline-content">
                <div class="timeline-title">用户评价</div>
                <div class="timeline-time">{{ formatDate(workOrder?.updatedAt) }}</div>
                <div class="timeline-desc">
                  {{ workOrder?.reporterNickName }} 对维修服务进行了评价
                  <a-rate v-if="workOrder?.rating" :value="workOrder.rating" disabled allow-half />
                </div>
              </div>
            </a-timeline-item>

            <a-timeline-item v-if="workOrder?.status === WorkOrderStatus.CANCELLED" color="red">
              <template #dot>
                <CloseCircleOutlined />
              </template>
              <div class="timeline-content">
                <div class="timeline-title">工单取消</div>
                <div class="timeline-time">{{ formatDate(workOrder?.updatedAt) }}</div>
                <div class="timeline-desc">工单已取消</div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>

        <!-- 操作区域 -->
        <div class="action-section">
          <h3>操作</h3>
          <a-space>
            <!-- 学生操作 -->
            <template
              v-if="userStore.isStudent && workOrder?.reporterId === userStore.userInfo?.id"
            >
              <a-button v-if="canCancel" type="danger" @click="handleCancel"> 取消工单 </a-button>
              <a-button
                v-if="workOrder?.status === WorkOrderStatus.COMPLETED"
                type="primary"
                @click="showReviewModal"
              >
                评价
              </a-button>
            </template>

            <!-- 维修工操作 -->
            <template v-if="userStore.isRepairWorker">
              <a-button
                v-if="workOrder?.status === WorkOrderStatus.PENDING"
                type="primary"
                @click="handleProcess"
              >
                接单处理
              </a-button>
              <a-button
                v-if="workOrder?.status === WorkOrderStatus.IN_PROGRESS"
                type="primary"
                @click="handleComplete"
              >
                完成维修
              </a-button>
            </template>

            <!-- 管理员操作 -->
            <template v-if="userStore.isAdmin">
              <a-button
                v-if="workOrder?.status === WorkOrderStatus.PENDING"
                type="primary"
                @click="handleAssign"
              >
                分配维修工
              </a-button>
              <a-button
                v-if="workOrder?.status !== WorkOrderStatus.CANCELLED"
                type="danger"
                @click="handleCancel"
              >
                取消工单
              </a-button>
            </template>
          </a-space>
        </div>
      </a-skeleton>
    </a-card>

    <!-- 评价弹窗 -->
    <a-modal
      v-model:open="reviewModalVisible"
      title="评价维修服务"
      @ok="handleReview"
      :confirm-loading="reviewLoading"
    >
      <a-form layout="vertical">
        <a-form-item label="服务评分">
          <a-rate v-model:value="reviewForm.rating" allow-half />
        </a-form-item>
        <a-form-item label="评价内容">
          <a-textarea
            v-model:value="reviewForm.reviewComment"
            placeholder="请输入您对本次维修服务的评价"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分配维修工弹窗 -->
    <AssignWorkerModal
      v-model:open="assignModalVisible"
      :work-order-id="workOrder?.id"
      @success="handleAssignSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getWorkOrderDetail, updateWorkOrder, reviewWorkOrder } from '@/api/workorder'
import { WorkOrderStatus } from '@/types'
import type { WorkOrder, WorkOrderReviewRequest } from '@/types'
import {
  FileAddOutlined,
  ToolOutlined,
  CheckCircleOutlined,
  StarOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons-vue'
import AssignWorkerModal from '@/components/WorkOrder/AssignWorkerModal.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

const loading = ref(true)
const workOrder = ref<WorkOrder>()

// 评价相关
const reviewModalVisible = ref(false)
const reviewLoading = ref(false)
const reviewForm = reactive<WorkOrderReviewRequest>({
  workOrderId: 0,
  rating: 5,
  reviewComment: '',
})

// 分配维修工相关
const assignModalVisible = ref(false)

// 计算属性
const canEdit = computed(() => {
  return (
    userStore.isStudent &&
    workOrder.value?.reporterId === userStore.userInfo?.id &&
    workOrder.value?.status === WorkOrderStatus.PENDING
  )
})

const canCancel = computed(() => {
  return (
    (userStore.isStudent &&
      workOrder.value?.reporterId === userStore.userInfo?.id &&
      (workOrder.value?.status === WorkOrderStatus.PENDING ||
        workOrder.value?.status === WorkOrderStatus.IN_PROGRESS)) ||
    userStore.isAdmin
  )
})

// 处理人
const handlerUser = computed(() => {
  if (workOrder.value?.handlerId == null) return '暂未分配'
  return workOrder.value?.handlerNickName + ' (' + workOrder.value?.handlerAccount + ')'
})

// 联系电话
const contactPhone = computed(() => {
  let res = '学生：' + workOrder.value?.reporterPhoneNumber + '\n' + '维修工：'
  if (workOrder.value?.handlerPhoneNumber) {
    res += workOrder.value?.handlerPhoneNumber
  } else {
    res += '暂未分配'
  }
  return res
})

// 获取状态颜色
const getStatusColor = (status?: WorkOrderStatus) => {
  if (!status) return 'default'

  const colorMap = {
    [WorkOrderStatus.PENDING]: 'orange',
    [WorkOrderStatus.IN_PROGRESS]: 'blue',
    [WorkOrderStatus.COMPLETED]: 'green',
    [WorkOrderStatus.REVIEWED]: 'purple',
    [WorkOrderStatus.CANCELLED]: 'red',
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status?: WorkOrderStatus) => {
  if (status == null) return '未知'
  const textMap = {
    [WorkOrderStatus.PENDING]: '待处理',
    [WorkOrderStatus.IN_PROGRESS]: '处理中',
    [WorkOrderStatus.COMPLETED]: '已完成',
    [WorkOrderStatus.REVIEWED]: '已评价',
    [WorkOrderStatus.CANCELLED]: '已取消',
  }
  return textMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 获取工单详情
const fetchWorkOrderDetail = async () => {
  try {
    loading.value = true
    const id = Number(route.params.id)
    if (isNaN(id)) {
      message.error('无效的工单ID')
      router.back()
      return
    }

    const response = await getWorkOrderDetail({ id })
    if (response.code === 0) {
      workOrder.value = response.data
    } else {
      message.error('获取工单详情失败')
      router.back()
    }
  } catch (error) {
    console.error('获取工单详情失败:', error)
    message.error('获取工单详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 编辑工单
const handleEdit = () => {
  router.push(`/workorder/edit/${workOrder.value?.id}`)
}

// 取消工单
const handleCancel = () => {
  Modal.confirm({
    title: '确认取消',
    content: '确定要取消此工单吗？此操作不可恢复。',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        if (!workOrder.value?.id) {
          message.error('工单ID不存在')
          return
        }
        const response = await updateWorkOrder({
          id: workOrder.value.id,
          status: WorkOrderStatus.CANCELLED,
        })
        if (response.code === 0) {
          message.success('工单已取消')
          fetchWorkOrderDetail()
        } else {
          message.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('取消工单失败:', error)
        message.error('操作失败，请重试')
      }
    },
  })
}

// 接单处理
const handleProcess = async () => {
  try {
    if (!workOrder.value?.id) {
      message.error('工单ID不存在')
      return
    }
    const response = await updateWorkOrder({
      id: workOrder.value.id,
      status: WorkOrderStatus.IN_PROGRESS,
    })
    if (response.code === 0) {
      message.success('已开始处理工单')
      fetchWorkOrderDetail()
    } else {
      message.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('处理工单失败:', error)
    message.error('操作失败，请重试')
  }
}

// 完成维修
const handleComplete = () => {
  Modal.confirm({
    title: '确认完成',
    content: '确定要将此工单标记为已完成吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        if (!workOrder.value?.id) {
          message.error('工单ID不存在')
          return
        }
        const response = await updateWorkOrder({
          id: workOrder.value.id,
          status: WorkOrderStatus.COMPLETED,
        })
        if (response.code === 0) {
          message.success('工单已完成')
          fetchWorkOrderDetail()
        } else {
          message.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('完成工单失败:', error)
        message.error('操作失败，请重试')
      }
    },
  })
}

// 分配维修工
const handleAssign = () => {
  assignModalVisible.value = true
}

// 分配成功回调
const handleAssignSuccess = () => {
  fetchWorkOrderDetail()
}

// 显示评价弹窗
const showReviewModal = () => {
  reviewForm.workOrderId = workOrder.value?.id || 0
  reviewForm.rating = 5
  reviewForm.reviewComment = ''
  reviewModalVisible.value = true
}

// 提交评价
const handleReview = async () => {
  try {
    reviewLoading.value = true
    const response = await reviewWorkOrder(reviewForm)
    if (response.code === 0) {
      message.success('评价提交成功')
      reviewModalVisible.value = false
      fetchWorkOrderDetail()
    }
  } catch (error) {
    console.error('提交评价失败:', error)
  } finally {
    reviewLoading.value = false
  }
}

onMounted(() => {
  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '工单管理', path: '/workorder/list' },
    { title: '工单详情' },
  ])

  fetchWorkOrderDetail()
})
</script>

<style scoped>
.workorder-detail {
  padding: 0;
}

.image-section,
.process-section,
.action-section {
  margin-top: 24px;
}

.workorder-image {
  margin-right: 8px;
  margin-bottom: 8px;
}

.timeline-content {
  display: flex;
  flex-direction: column;
}

.timeline-title {
  font-weight: 600;
}

.timeline-time {
  font-size: 12px;
  color: #999;
  margin: 4px 0;
}

.timeline-desc {
  color: #666;
}
</style>
